﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/

using Longbow.Tasks.EntityFrameworkCore.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;

namespace Longbow.Tasks.EntityFrameworkCoreStorage
{
    /// <summary>
    /// 
    /// </summary>
    public static class EFCoreStorageExtension
    {
        /// <summary>
        /// 增加 EFCore 持久化扩展服务
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configureOptions"></param>
        /// <param name="optionsBuilder"></param>
        /// <returns></returns>
        public static ITaskStorageBuilder AddEntityFrameworkCoreStorage<TStorage>(this ITaskStorageBuilder builder,
            Action<EntityFrameworkCoreStorageOptions>? configureOptions = null, Action<DbContextOptionsBuilder>? optionsBuilder = null) where TStorage : EFCoreStorage
        {
            builder.Services.AddSingleton<IStorage, TStorage>();
            builder.Services.AddSingleton<IOptionsChangeTokenSource<EntityFrameworkCoreStorageOptions>, ConfigurationChangeTokenSource<EntityFrameworkCoreStorageOptions>>();
            builder.Services.AddSingleton<IConfigureOptions<EntityFrameworkCoreStorageOptions>, EFCoreStorageOptionsConfigureOption<EntityFrameworkCoreStorageOptions>>();
            builder.Services.AddDbContext<SchedulerDBContext>(optionsBuilder, ServiceLifetime.Singleton, ServiceLifetime.Singleton);

            if (configureOptions != null)
            {
                builder.Services.Configure(configureOptions);
            }
            return builder;
        }
    }
}
